// 2025/6/9: 首个版本

using System;
using System.Collections.Generic;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using ASEva.Utility;

namespace CommonSource;

// 需要库文件：IronPython.dll, IronPython.Modules.dll, IronPython.SQLite.dll, Microsoft.Dynamic.dll, Microsoft.Scripting.dll, Microsoft.Scripting.Metadata.dll, System.CodeDom.dll
// 需要在csproj中引用：IronPython.dll, IronPython.Modules.dll, Microsoft.Scripting.dll

class PythonRunner
{
    public static Dictionary<String, object> Run(String script, Dictionary<String, object> inputValues, String[] outputNames)
    {
        try
        {
            if (engine == null) 
            {
                engine = Python.CreateEngine();
            }

            var scope = engine.CreateScope();
            foreach (var pair in inputValues)
            {
                scope.SetVariable(pair.Key, pair.Value);
            }

            engine.Execute(script, scope);
            
            var outputValues = new Dictionary<String, object>();
            foreach (var name in outputNames)
            {
                if (scope.ContainsVariable(name))
                {
                    outputValues[name] = scope.GetVariable(name);
                }
                else
                {
                    outputValues[name] = null;
                }
            }

            return outputValues;
        }
        catch (Exception ex)
        {
            Dump.Exception(ex);
            return null;
        }
    }

    private static ScriptEngine engine = null;

    public static void RunTest()
    {
        var t0 = DateTime.Now;
        var outputValues = PythonRunner.Run(testScript,
            inputValues: new()
            {
                ["text"] = "Hello world",
                ["number"] = 5.5,
                ["multiply"] = true,
            },
            outputNames:
            [
                "output"
            ]);
        var costTime = (DateTime.Now - t0).TotalMilliseconds;
        Console.WriteLine("output=" + outputValues["output"] + " costTime=" + costTime + "ms");
    }

private static String testScript = @"
text_length = len(text)
if multiply:
    output = text_length * number
else:
    output = text_length + number";
}